package yuan.zk.global_unique_id;

import org.apache.zookeeper.*;
import yuan.zk.node.ZKCreate;
import yuan.zk.watcher.ZKConnectionWatcher;

import java.util.concurrent.CountDownLatch;

/**
 * @version: 1.0
 * @Description: TODO
 * @author: zZmH
 * @date: 2020/09/11 18:58
 */


public class GloballyUniqueId implements Watcher {

    public static final String ip = "192.168.190.128:2181";
    public static final int TIME_OUT = 5000;
    private ZooKeeper zooKeeper;
    CountDownLatch latch = new CountDownLatch(1);
    String defaultPath = "/uniqueId";

    @Override
    public void process(WatchedEvent event) {
        try {
            if (event.getType() == Event.EventType.None) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    System.out.println("connected successfully!");
                    latch.countDown();
                } else if (event.getState() == Event.KeeperState.Disconnected) {
                    System.out.println("shutdown the connection!");

                } else if (event.getState() == Event.KeeperState.Expired) {
                    System.out.println("session timeout!");
                    zooKeeper = new ZooKeeper(ZKCreate.ip, ZKCreate.TIME_OUT,
                            new ZKConnectionWatcher());
                } else if (event.getState() == Event.KeeperState.AuthFailed) {
                    System.out.println("authentication failure!");

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public GloballyUniqueId() {
        try {
            zooKeeper = new ZooKeeper(ip, TIME_OUT, this);
            latch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getUniqueId(){
        String path = "";
        try {
            path = zooKeeper.create(defaultPath, new byte[0],
                    ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.EPHEMERAL_SEQUENTIAL);
        } catch (Exception e) {

        }
        return path.substring(9);

    }

    public static void main(String[] args) {
        GloballyUniqueId globallyUniqueId = new GloballyUniqueId();
        for (int i = 0; i < 10; i++) {
            System.out.println(globallyUniqueId.getUniqueId());
        }
    }
}
